/**
 * 
 */
package qy.jalgotrade.utils;

import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;

/**
 * @author qy
 *
 */
public class FastUtilLongArrayListDeque implements PySpecs.SeqGetItem<Long> {

	private LongArrayList __values;

	private int __maxLen;

	private int __nextPos;

	public FastUtilLongArrayListDeque(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";
		__maxLen = maxLen;
		__nextPos = 0;
		__values = new LongArrayList();
	}

	/**
	 * 
	 * @return
	 */
	public int getMaxLen() {

		return __maxLen;
	}

	/**
	 * 
	 * @param value
	 */
	public void append(long value) {

		if (__nextPos < __maxLen) {
			__values.add(__nextPos, value);
			__nextPos++;
		} else {
			/*
			 * Shift items to the left and put the last value.
			 * I'm not using np.roll to avoid creating a new array.
			 */
			__values.removeLong(0);
			__values.add(__nextPos - 1, value);
		}
	}

	/**
	 * 
	 * @return
	 */
	public LongList data() {

		// If all values are not initialized, return a portion of the array.
		if (__nextPos < __maxLen) {
			return __values.subList(0, __nextPos);
		} else {
			return __values;
		}
	}

	/**
	 * 
	 * @return
	 */
	public long[] toPrimitiveArray() {

		// If all values are not initialized, return a portion of the array.
		long[] ret = new long[__len__()];
		__values.getElements(0, ret, 0, ret.length);
		return ret;
	}

	/**
	 * 
	 * @param maxLen
	 */
	public void resize(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";

		LongList lastValues = __values.subList(0, __nextPos);
		int startIdx = lastValues.size() - maxLen;
		if (startIdx > 0) {
			// Create empty, copy last values and swap.
			LongArrayList values = new LongArrayList(lastValues.size());
			values.addAll(startIdx, lastValues);
			__values = values;
		}

		__maxLen = maxLen;
		if (__nextPos >= __maxLen) {
			__nextPos = __maxLen;
		}
	}

	@Override
	public int __len__() {

		return __nextPos;
	}

	@Override
	public Long __getitem__(int idx) {

		if (idx < 0) {
			idx += __len__();
		}
		return __values.getLong(idx);
	}

	@Override
	public String toString() {

		return __values.toString();
	}
}
